<template>
  <Dialog v-model="dialogVisible" title="菜单权限" class="enhanced-dialog" width="50%">
    <!-- 弹窗头部 -->
    <div class="dialog-header">
      <div class="header-icon">
        <Icon icon="ep:menu" />
      </div>
      <div class="header-content">
        <h4 class="dialog-title">菜单权限配置</h4>
        <p class="dialog-subtitle">配置角色的菜单访问权限</p>
      </div>
    </div>

    <!-- 表单内容 -->
    <div class="form-container">
      <el-form
        ref="formRef"
        v-loading="formLoading"
        :model="formData"
        label-width="80px"
        class="enhanced-form"
      >
        <el-form-item label="角色名称" class="form-item">
          <div class="tag-container">
            <Icon icon="ep:user" class="tag-icon" />
            <el-tag class="enhanced-tag role-tag">{{ formData.name }}</el-tag>
          </div>
        </el-form-item>

        <el-form-item label="角色标识" class="form-item">
          <div class="tag-container">
            <Icon icon="ep:key" class="tag-icon" />
            <el-tag class="enhanced-tag code-tag">{{ formData.code }}</el-tag>
          </div>
        </el-form-item>

        <!-- 菜单权限配置 -->
        <div class="menu-permission-section">
          <div class="section-title">
            <Icon icon="ep:menu" class="section-icon" />
            <span>菜单权限配置</span>
          </div>

          <el-card class="enhanced-card" shadow="never">
            <template #header>
              <div class="card-header">
                <div class="control-group">
                  <div class="control-item">
                    <span class="control-label">全选/全不选:</span>
                    <el-switch
                      v-model="treeNodeAll"
                      active-text="是"
                      inactive-text="否"
                      inline-prompt
                      @change="handleCheckedTreeNodeAll"
                      class="enhanced-switch"
                    />
                  </div>
                  <div class="control-item">
                    <span class="control-label">全部展开/折叠:</span>
                    <el-switch
                      v-model="menuExpand"
                      active-text="展开"
                      inactive-text="折叠"
                      inline-prompt
                      @change="handleCheckedTreeExpand"
                      class="enhanced-switch"
                    />
                  </div>
                </div>
              </div>
            </template>

            <div class="tree-container">
              <el-tree
                ref="treeRef"
                :data="menuOptions"
                :props="defaultProps"
                empty-text="加载中，请稍候"
                node-key="id"
                show-checkbox
                class="enhanced-tree"
              />
            </div>
          </el-card>
        </div>
      </el-form>
    </div>

    <!-- 弹窗底部 -->
    <template #footer>
      <div class="dialog-footer">
        <el-button :disabled="formLoading" type="primary" @click="submitForm" class="submit-btn">
          <Icon icon="ep:check" class="btn-icon" />
          确 定
        </el-button>
        <el-button @click="dialogVisible = false" class="cancel-btn">
          <Icon icon="ep:close" class="btn-icon" />
          取 消
        </el-button>
      </div>
    </template>
  </Dialog>
</template>

<script lang="ts" setup>
import { defaultProps, handleTree } from '@/utils/tree'
import * as RoleApi from '@/api/system/role'
import * as MenuApi from '@/api/system/menu'
import * as PermissionApi from '@/api/system/permission'

defineOptions({ name: 'SystemRoleAssignMenuForm' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formData = reactive({
  id: 0,
  name: '',
  code: '',
  menuIds: [],
  tenantId: null
})
const formRef = ref() // 表单 Ref
const menuOptions = ref<any[]>([]) // 菜单树形结构
const menuExpand = ref(false) // 展开/折叠
const treeRef = ref() // 菜单树组件 Ref
const treeNodeAll = ref(false) // 全选/全不选

/** 打开弹窗 */
const open = async (row: RoleApi.RoleVO, userId) => {
  dialogVisible.value = true
  resetForm()
  formData.tenantId = userId
  // 加载 Menu 列表。注意，必须放在前面，不然下面 setChecked 没数据节点
  menuOptions.value = handleTree(await MenuApi.getSimpleMenusList())
  // 设置数据
  formData.id = row.id
  formData.name = row.name
  formData.code = row.code
  formLoading.value = true
  try {
    formData.value.menuIds = await PermissionApi.getRoleMenuListAdmin({
      roleId: row.id,
      tenantId: userId
    })
    // 设置选中
    formData.value.menuIds.forEach((menuId: number) => {
      treeRef.value.setChecked(menuId, true, false)
    })
  } finally {
    formLoading.value = false
  }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  if (!formRef) return
  const valid = await formRef.value.validate()
  if (!valid) return
  // 提交请求
  formLoading.value = true
  try {
    const data = {
      roleId: formData.id,
      menuIds: [
        ...(treeRef.value.getCheckedKeys(false) as unknown as Array<number>), // 获得当前选中节点
        ...(treeRef.value.getHalfCheckedKeys() as unknown as Array<number>) // 获得半选中的父节点
      ],
      tenantId: formData.tenantId
    }
    await PermissionApi.assignRoleMenuAdmin(data)
    message.success(t('common.updateSuccess'))
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  // 重置选项
  treeNodeAll.value = false
  menuExpand.value = false
  // 重置表单
  formData.value = {
    id: 0,
    name: '',
    code: '',
    menuIds: []
  }
  treeRef.value?.setCheckedNodes([])
  formRef.value?.resetFields()
}

/** 全选/全不选 */
const handleCheckedTreeNodeAll = () => {
  treeRef.value.setCheckedNodes(treeNodeAll.value ? menuOptions.value : [])
}

/** 展开/折叠全部 */
const handleCheckedTreeExpand = () => {
  const nodes = treeRef.value?.store.nodesMap
  for (let node in nodes) {
    if (nodes[node].expanded === menuExpand.value) {
      continue
    }
    nodes[node].expanded = menuExpand.value
  }
}
</script>

<style lang="scss" scoped>
// 主题色变量
$primary-color: #0052cc;
$primary-light: rgba(0, 82, 204, 0.1);
$primary-border: rgba(0, 82, 204, 0.3);
$success-color: #67c23a;
$warning-color: #e6a23c;
$danger-color: #f56c6c;
$info-color: #909399;
$text-primary: #303133;
$text-regular: #606266;
$text-secondary: #909399;
$text-placeholder: #c0c4cc;
$border-color: #dcdfe6;
$border-light: #e4e7ed;
$bg-color: #f5f7fa;
$shadow-light: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
$shadow-base:
  0 2px 4px rgba(0, 0, 0, 0.12),
  0 0 6px rgba(0, 0, 0, 0.04);
$border-radius: 12px;
$border-radius-small: 8px;

/* 弹窗样式 */
.enhanced-dialog {
  :deep(.el-dialog) {
    border-radius: $border-radius;
    overflow: hidden;

    @media (max-width: 768px) {
      width: 95% !important;
      margin: 0 auto;
    }
  }

  :deep(.el-dialog__header) {
    padding: 0;
    border-bottom: none;
  }

  :deep(.el-dialog__body) {
    padding: 0;
  }

  :deep(.el-dialog__footer) {
    padding: 0;
    border-top: none;
  }

  :deep(.el-dialog__headerbtn) {
    top: 16px;
    right: 16px;
    z-index: 10;

    .el-dialog__close {
      color: white;
      font-size: 18px;

      &:hover {
        color: rgba(255, 255, 255, 0.8);
      }
    }
  }
}

/* 弹窗头部 */
.dialog-header {
  display: flex;
  align-items: center;
  padding: 20px 24px;
  background: linear-gradient(135deg, $primary-color 0%, #1d4ed8 100%);
  color: white;

  @media (max-width: 768px) {
    padding: 16px 20px;
    flex-direction: column;
    gap: 8px;
    text-align: center;
  }
}

.header-icon {
  width: 40px;
  height: 40px;
  background: rgba(255, 255, 255, 0.2);
  border-radius: $border-radius-small;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 18px;
  flex-shrink: 0;

  @media (max-width: 768px) {
    width: 36px;
    height: 36px;
    font-size: 16px;
  }
}

.header-content {
  flex: 1;
  margin-left: 12px;

  @media (max-width: 768px) {
    margin-left: 0;
  }
}

.dialog-title {
  font-size: 18px;
  font-weight: 600;
  margin: 0 0 4px 0;

  @media (max-width: 768px) {
    font-size: 16px;
  }
}

.dialog-subtitle {
  font-size: 13px;
  opacity: 0.9;
  margin: 0;

  @media (max-width: 768px) {
    font-size: 12px;
  }
}

/* 表单容器 */
.form-container {
  padding: 24px;
  background: white;
  max-height: 70vh;
  overflow-y: auto;

  @media (max-width: 768px) {
    padding: 16px;
    max-height: 60vh;
  }

  /* 滚动条美化 */
  &::-webkit-scrollbar {
    width: 6px;
  }

  &::-webkit-scrollbar-track {
    background: rgba(0, 0, 0, 0.05);
    border-radius: 3px;
  }

  &::-webkit-scrollbar-thumb {
    background: rgba(0, 82, 204, 0.3);
    border-radius: 3px;
    transition: all 0.3s ease;

    &:hover {
      background: rgba(0, 82, 204, 0.5);
    }
  }
}

.enhanced-form {
  .form-item {
    margin-bottom: 20px;

    @media (max-width: 768px) {
      margin-bottom: 16px;
    }

    :deep(.el-form-item__label) {
      font-weight: 600;
      color: $text-regular;
      padding-bottom: 8px;

      @media (max-width: 768px) {
        font-size: 14px;
        width: 100% !important;
        text-align: left !important;
        margin-bottom: 8px;
      }
    }

    :deep(.el-form-item__content) {
      @media (max-width: 768px) {
        margin-left: 0 !important;
      }
    }
  }

  // H5适配：表单项垂直布局
  @media (max-width: 768px) {
    :deep(.el-form-item) {
      display: block;
    }
  }
}

/* 标签容器 */
.tag-container {
  display: flex;
  align-items: center;
  gap: 8px;
}

.tag-icon {
  color: $primary-color;
  font-size: 16px;
}

.enhanced-tag {
  border-radius: 6px;
  font-weight: 500;
  padding: 6px 12px;
  font-size: 13px;
  display: flex;
  align-items: center;
  gap: 4px;

  &.role-tag {
    background: $primary-light;
    color: $primary-color;
    border: 1px solid $primary-border;
  }

  &.code-tag {
    background: rgba(230, 162, 60, 0.1);
    color: $warning-color;
    border: 1px solid rgba(230, 162, 60, 0.3);
  }

  @media (max-width: 768px) {
    font-size: 12px;
    padding: 4px 8px;
  }
}

/* 菜单权限配置区域 */
.menu-permission-section {
  margin-top: 24px;

  @media (max-width: 768px) {
    margin-top: 20px;
  }
}

.section-title {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 16px;
  padding-bottom: 8px;
  border-bottom: 2px solid $primary-light;
  font-size: 16px;
  font-weight: 600;
  color: $text-primary;

  @media (max-width: 768px) {
    font-size: 14px;
    margin-bottom: 12px;
    padding-bottom: 6px;
  }
}

.section-icon {
  color: $primary-color;
  font-size: 18px;

  @media (max-width: 768px) {
    font-size: 16px;
  }
}

/* 卡片样式 */
.enhanced-card {
  border-radius: $border-radius-small;
  box-shadow: $shadow-base;
  border: 1px solid $border-light;
  overflow: hidden;

  :deep(.el-card__header) {
    background: linear-gradient(135deg, #f8f9ff 0%, #f0f2ff 100%);
    border-bottom: 1px solid $border-light;
    padding: 16px 20px;

    @media (max-width: 768px) {
      padding: 12px 16px;
    }
  }

  :deep(.el-card__body) {
    padding: 20px;

    @media (max-width: 768px) {
      padding: 16px;
    }
  }
}

.card-header {
  .control-group {
    display: flex;
    flex-wrap: wrap;
    gap: 20px;
    align-items: center;

    @media (max-width: 768px) {
      flex-direction: column;
      gap: 12px;
      align-items: stretch;
    }
  }

  .control-item {
    display: flex;
    align-items: center;
    gap: 8px;
    flex: 1;
    min-width: 200px;

    @media (max-width: 768px) {
      min-width: auto;
      justify-content: space-between;
    }
  }

  .control-label {
    font-size: 14px;
    color: $text-regular;
    font-weight: 500;
    white-space: nowrap;

    @media (max-width: 768px) {
      font-size: 13px;
    }
  }
}

.enhanced-switch {
  :deep(.el-switch__core) {
    background: $border-color;
    border-color: $border-color;

    &.is-checked {
      background: $primary-color;
      border-color: $primary-color;
    }
  }

  :deep(.el-switch__action) {
    background: white;
  }
}

/* 树形组件容器 */
.tree-container {
  max-height: 400px;
  overflow-y: auto;
  border: 1px solid $border-light;
  border-radius: $border-radius-small;
  padding: 12px;

  @media (max-width: 768px) {
    max-height: 300px;
    padding: 8px;
  }

  /* 滚动条美化 */
  &::-webkit-scrollbar {
    width: 6px;
  }

  &::-webkit-scrollbar-track {
    background: rgba(0, 0, 0, 0.05);
    border-radius: 3px;
  }

  &::-webkit-scrollbar-thumb {
    background: rgba(0, 82, 204, 0.3);
    border-radius: 3px;
  }
}

.enhanced-tree {
  :deep(.el-tree-node) {
    .el-tree-node__content {
      padding: 8px 12px;
      border-radius: 6px;
      margin: 2px 0;
      transition: all 0.3s ease;

      &:hover {
        background: $primary-light;
      }

      @media (max-width: 768px) {
        padding: 6px 8px;
        font-size: 14px;
      }
    }

    .el-tree-node__expand-icon {
      color: $primary-color;
      font-size: 14px;

      &:hover {
        color: darken($primary-color, 10%);
      }
    }

    .el-checkbox {
      :deep(.el-checkbox__input) {
        .el-checkbox__inner {
          border-color: $border-color;
          transition: all 0.3s ease;

          &:hover {
            border-color: $primary-color;
          }
        }

        &.is-checked {
          .el-checkbox__inner {
            background: $primary-color;
            border-color: $primary-color;
          }
        }
      }
    }
  }
}

/* 弹窗底部 */
.dialog-footer {
  display: flex;
  justify-content: center;
  gap: 12px;
  padding: 20px 24px;
  background: #fafbff;
  border-top: 1px solid $border-light;

  @media (max-width: 768px) {
    padding: 16px 20px;
    flex-direction: column;
  }
}

.submit-btn {
  background: linear-gradient(135deg, $primary-color 0%, #1d4ed8 100%);
  border: none;
  border-radius: $border-radius-small;
  padding: 12px 24px;
  font-weight: 500;
  color: white;
  transition: all 0.3s ease;
  display: flex;
  align-items: center;
  gap: 6px;

  &:hover {
    transform: translateY(-2px);
    box-shadow: 0 4px 12px rgba(0, 82, 204, 0.3);
  }

  &:disabled {
    opacity: 0.6;
    cursor: not-allowed;
    transform: none;
  }

  @media (max-width: 768px) {
    width: 100%;
    justify-content: center;
  }

  .btn-icon {
    font-size: 14px;
  }
}

.cancel-btn {
  border: 2px solid $border-color;
  color: $text-regular;
  border-radius: $border-radius-small;
  padding: 12px 24px;
  font-weight: 500;
  transition: all 0.3s ease;
  display: flex;
  align-items: center;
  gap: 6px;

  &:hover {
    border-color: $primary-color;
    color: $primary-color;
    background: $primary-light;
  }

  @media (max-width: 768px) {
    width: 100%;
    justify-content: center;
  }

  .btn-icon {
    font-size: 14px;
  }
}

/* 加载状态优化 */
:deep(.el-loading-mask) {
  background: rgba(255, 255, 255, 0.9);
  backdrop-filter: blur(2px);

  .el-loading-spinner {
    .path {
      stroke: $primary-color;
    }
  }
}

/* 深色模式适配 */
@media (prefers-color-scheme: dark) {
  .form-container {
    background: #374151;
  }

  .dialog-footer {
    background: #4b5563;
    border-color: #6b7280;
  }

  .section-title {
    color: #f9fafb;
    border-color: rgba(96, 165, 250, 0.3);
  }

  .enhanced-form {
    .form-item {
      :deep(.el-form-item__label) {
        color: #d1d5db;
      }
    }
  }

  .enhanced-tag {
    &.role-tag {
      background: rgba(96, 165, 250, 0.1);
      color: #60a5fa;
      border-color: rgba(96, 165, 250, 0.3);
    }

    &.code-tag {
      background: rgba(251, 191, 36, 0.1);
      color: #fbbf24;
      border-color: rgba(251, 191, 36, 0.3);
    }
  }

  .enhanced-card {
    background: #374151;
    border-color: #4b5563;

    :deep(.el-card__header) {
      background: #4b5563;
      border-color: #6b7280;
    }

    :deep(.el-card__body) {
      background: #374151;
    }
  }

  .control-label {
    color: #d1d5db;
  }

  .tree-container {
    background: #374151;
    border-color: #4b5563;
  }

  .enhanced-tree {
    :deep(.el-tree-node) {
      .el-tree-node__content {
        color: #f9fafb;

        &:hover {
          background: rgba(96, 165, 250, 0.1);
        }
      }

      .el-tree-node__expand-icon {
        color: #60a5fa;
      }

      .el-checkbox {
        :deep(.el-checkbox__input) {
          .el-checkbox__inner {
            background: #4b5563;
            border-color: #6b7280;
          }

          &.is-checked {
            .el-checkbox__inner {
              background: #60a5fa;
              border-color: #60a5fa;
            }
          }
        }
      }
    }
  }
}

/* 响应式优化 */
@media (max-width: 480px) {
  .dialog-header {
    padding: 12px 16px;
  }

  .form-container {
    padding: 12px;
  }

  .enhanced-form {
    .form-item {
      margin-bottom: 12px;

      :deep(.el-form-item__label) {
        font-size: 13px;
      }
    }
  }

  .section-title {
    font-size: 13px;
    margin-bottom: 10px;
    padding-bottom: 4px;
  }

  .enhanced-card {
    :deep(.el-card__header) {
      padding: 10px 12px;
    }

    :deep(.el-card__body) {
      padding: 12px;
    }
  }

  .control-group {
    gap: 8px;
  }

  .control-label {
    font-size: 12px;
  }

  .tree-container {
    max-height: 250px;
    padding: 6px;
  }

  .dialog-footer {
    padding: 12px 16px;
    gap: 8px;
  }
}
</style>
